import Dialog from '@vant/weapp/dialog/dialog';
import axios from '../../utils/axios';
const Multipart = require('../../utils/Multipart.min.js')
// pages/verify/verify.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userdetail:{},
    fileList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function(option) {
    var userdetail=JSON.parse(option.userdetail)

    this.setData({
      userdetail:userdetail
    })
    console.log(userdetail)
  },
  del(event){
    let id = event.detail.index   //能获取到对应的下标
    let fileList = this.data.fileList  //这里是前端页面展示的数组
    fileList.splice(id,1)     //根据下标来删除对应的图片
    this.setData({
      fileList:fileList,  //在这里进行重新赋值  删除后 图片剩几张就相当于给后台传几张
    })
 },
  afterRead(event) {
    var files = event.detail.file;
    var fileList=this.data.fileList
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      file.url=file.path
    fileList.push(file)
    }
    this.setData({
       fileList:fileList
     })
   
  },
  async submit(){
    var that=this
    console.log(this.data.fileList)
   wx.showModal({
     title: "确定发布吗",
     success:async function(res){
       if(res.confirm){
        let fileList=that.data.fileList
        var files=[];  //构建的promise数组
         fileList.forEach((item)=>{  //item为图片的url
          var file={filePath:item.tempFilePath}
          files.push(file)
         })
         const field=that.data.userdetail
         console.log(field)
       var fields = Object.keys(field).map(key => ({
          name: key,
          value: field[key]
        }))
        console.log(fields)
          files.map((item) => {
            return Object.assign(item, {
              name: "file",filePath:item.filePath })
          });
          console.log(files)
          await axios.upload('/user/auth',fields,files)
          await that.logininit()
       }
     }
   })
   
  },
  async logininit(){
    var app=getApp()
      const {code:code}= await wx.p.login({})
      var baseUrl=axios.baseUrl
      wx.request({
        url:baseUrl+'/accesstoken?code='+code,
        method:"POST",
        success:res=>{
          console.log(res)
          var accessToken=res.data.accesstoken
          var user=res.data.user
          app.globalData.accessToken = accessToken;
          app.globalData.user=user;
          setTimeout(() => {
            wx.switchTab({
              url:"../calendar/calendar"
            })  
          }, 200);
        }
      })
      
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})